#include <func.h>

#define MAXLINE 256

int main(int argc, char* argv[])
{
	// 1. 关联两根管道
	// 破坏循环等待条件，避免出现死锁现象
	int writefd = open("pipe1", O_WRONLY); // 阻塞点
	if (writefd == -1) {
		error(1, errno, "open pipe1");
	}

	int readfd = open("pipe2", O_RDONLY);
	if (readfd == -1) {
		error(1, errno, "open pipe2");
	}

	printf("Conenection Established\n");

	fd_set mainset; // 监听读事件的文件描述符集合

	FD_ZERO(&mainset);
	FD_SET(STDIN_FILENO, &mainset);
	int maxfd = STDIN_FILENO;

	FD_SET(readfd, &mainset);
	if (readfd > maxfd) {
		maxfd = readfd;
	}

	char recvline[MAXLINE];
	char sendline[MAXLINE];

	for(;;) {
		fd_set readfds = mainset;
		int nfds = select(maxfd + 1, &readfds, NULL, NULL, NULL);
		if (nfds == -1) {
			error(1, errno, "select");
		}
		if (FD_ISSET(STDIN_FILENO, &readfds)) {
			// stdin读事件就绪：用户输入了数据
			fgets(sendline, MAXLINE, stdin);
			write(writefd, sendline, strlen(sendline) + 1); // +1 for '\0'
		}
		if (FD_ISSET(readfd, &readfds)) {
			// 读管道事件就绪：对方发送了数据
			int n = read(readfd, recvline, MAXLINE);
			if (n <= 0) {
				goto end;
			}
			printf("%s", recvline);
		}
	}

end:
	close(readfd);
	close(writefd);
    return 0;
}
